/*
 * Copyright Hundsun Technologies Inc. All Rights Reserved.
 */

package state

// register the State store driver
import (
	"fmt"

	"hundsun.com/hsl/hschain/common/types"

	"hundsun.com/hsl/hschain/common/config"
	dbm "hundsun.com/hsl/hschain/store/db"
)

type stateCreate func(cfg *config.PluginConfig, db dbm.Database) (State, error)

var (
	regState = make(map[string]stateCreate)
	// EmptyRoot 空的根hash
	EmptyRoot [32]byte
)

// Register 注册 state driver
func Register(name string, create stateCreate) {
	if create == nil {
		panic("State: Register driver is nil")
	}
	if _, dup := regState[name]; dup {
		panic(fmt.Sprintf("State: driver %s has Registered", name))
	}
	regState[name] = create
}

// New 根据name的名称创建不同类型状态db
func New(cfg *config.PluginConfig, db dbm.Database) (State, error) {
	creator, ok := regState[cfg.Name]
	if !ok {
		fmt.Printf("NewState: Register have not find %s driver", cfg.Name)
		return nil, types.ErrNotFound
	}
	c, err := creator(cfg, db)
	if err != nil {
		return nil, err
	}
	// 检查状态数据类型是否一致
	info, _ := c.GetStateInfo()
	if info != nil && info.GetTy() != cfg.Name {
		panic(fmt.Sprintf("can not switch different state type from %s to %s", info.GetTy(), cfg.Name))
	}
	return c, nil
}
